package com.mjt.dongbao.common.base.interceptor;

import com.mjt.dongbao.common.base.annotation.TokenCheck;
import com.mjt.dongbao.common.base.execption.TokenExecption;
import com.mjt.dongbao.common.util.JwtUtil.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Description： 解析自定义的 @TokenCheck 注解
 * @Author mjt
 * @Time 2022/1/13
 */
public class TokenInterceptor implements HandlerInterceptor {

    /**
     * 
     * @Description: 
     * @Author mjt
     * @Date 2022/1/20
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 header 中获取 token
        String token = request.getHeader("token");

        // 对 token 判空
        if (StringUtils.isBlank(token)){
            throw new TokenExecption("Token 为空！");
        }

        // 获取到处理请求的 api 方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 检查方法上是否添加了 @TokenCheck 注解
        if (method.isAnnotationPresent(TokenCheck.class)){
            // 获取到 @TokenCheck 注解信息
            TokenCheck annotation = method.getAnnotation(TokenCheck.class);

            // 注解属性指定是否校验 token
            if (annotation.required()){
                // 校验token
                try {
                    JwtUtil.parseToken(token);
                    return true;
                }catch (Exception e){
                    throw new TokenExecption("Token 异常！");
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
